package structure.helpercalss;

import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * @AUTHOR LYF
 * @DATE 2022/3/18
 * @VERSION 1.0
 * @DESC
 */
public class SemaphoreDemo {
    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(5);//五个许可证

//        private final Semaphore.Sync sync;
//
//        /**
//         * Synchronization implementation for semaphore.  Uses AQS state
//         * to represent permits. Subclassed into fair and nonfair
//         * versions.
//         */
//        abstract static class Sync extends AbstractQueuedSynchronizer


        ArrayList list = new ArrayList();
        CountDownLatch countDownLatch = new CountDownLatch(5);

        // 十个人来抢资源
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                try {
                    String username = Thread.currentThread().getName()+"- user";
                    System.out.println(username+"来抢资源了！！！");
                    semaphore.acquire(1);
                    System.out.println(username+"抢到了！！！");
                    list.add(username);
//                    Integer random = new Random().nextInt(3);
//                    TimeUnit.SECONDS.sleep(random);
//                    System.out.println(username+"占用了"+random+"s,准备释放");
//                    semaphore.release(1);
//                    System.out.println(username+"释放一个资源");
                    countDownLatch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }

         countDownLatch.await();
        System.out.println("抢到的用户有:");
        list.forEach(u->{
            System.out.println(u);
        });

    }


}
